import logging

import allure
from selenium.common import TimeoutException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from core.keywords import Keywords


class BusinessKeywords(Keywords):
    def find_bk(self,by,value):
        wait = WebDriverWait(self.driver, 10)
        locator = (by, value)
        try:
            return wait.until(expected_conditions.presence_of_element_located(locator))
        except TimeoutException as e:
            logging.info(f"❌元素不存在--元素位置（{by},{value}）")
    def login(self,step,all):
        with allure.step(f"第{step['step_num']}步：{step['step_name']}"):
            logging.info(f"第{step['step_num']}步：{step['step_name']}-元素位置（{step['by']},{step['value']}）-数据{step['data']}-组元素索引{step['index']}")
            self.driver.get("http://192.168.10.130/login?redirect=%2Findex")
            login_dict=eval(step["data"])
            self.find_bk("xpath","//*[@placeholder='账号']").send_keys(login_dict["username"])
            self.find_bk("xpath","//*[@placeholder='密码']").send_keys(login_dict["password"])
            self.find_bk("xpath","//*[@placeholder='验证码']").send_keys(login_dict["code"])
            self.find_bk("xpath","//*[text()='登 录']").click()

    def get_attribute(self,step,all):
        with allure.step(f"第{step['step_num']}步：{step['step_name']}"):
            logging.info(f"第{step['step_num']}步：{step['step_name']}-元素位置（{step['by']},{step['value']}）-数据{step['data']}-组元素索引{step['index']}")
            #提取元素属性值到全局属性all中，用于动态元素的某个属性值，以便后续动态元素的定位
            for key,value in eval(step["data"]).items():
                value=self.find(step).get_attribute(value)
                all[key]=value
            logging.info(f"根据{step['data']}提取数据，此时全局属性all为{all}")


